import { _decorator, Component, Prefab, SpriteFrame, Texture2D, Node, Material, macro, director } from 'cc';
import {
    EntityTypeEnum, initGlobal, initChapter, initLevelPart, initWeapon, initProp, initEnemy,
    initSelectPool, initEntity, initExp, initActor, initAttribute, initSkill, initTalent
} from '../Common';
import ResourcesManager from '../Runtime/ResourcesManager';
import { JsonManager } from '../Runtime/JsonManager';
import CCCExtend from '../Utils/CCCExtend';
import { DynamicAtlasManager } from 'cc';
import { SceneEnum } from '../Enum';
const { ccclass, property } = _decorator;
macro.CLEANUP_IMAGE_CACHE = false;
DynamicAtlasManager.instance.enabled = true;

@ccclass('LoadScene')
export class LoadScene extends Component {

    @property(Node)
    run0: Node = null
    @property(Node)
    run1: Node = null
    @property(Node)
    run2: Node = null
    @property(Node)
    run3: Node = null

    curTime: number = 0
    async onLoad() {
        CCCExtend.init()

        const wait: Promise<unknown>[] = []

        this.loadJson(wait)
        this.loadResByEntityType(wait)
        this.loadMaterial(wait)
        this.loadPrefab(wait)

        await Promise.all(wait)
        director.loadScene(SceneEnum.Login)
    }
    loadJson(wait: Promise<unknown>[]) {

        JsonManager.Ins.getBundleJson().then(() => {
            wait.push(
                JsonManager.Ins.getValue('global').then((data: any) => {
                    initGlobal(data)
                    console.log('=== 加载完成 global json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('weapon').then((data: any) => {
                    initWeapon(data)
                    console.log('=== 加载完成 weapon json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('prop').then((data: any) => {
                    initProp(data)
                    console.log('=== 加载完成 prop json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('exp').then((data: any) => {
                    initExp(data)
                    console.log('=== 加载完成 exp json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('enemy').then((data: any) => {
                    initEnemy(data)
                    console.log('=== 加载完成 enemy json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('selectPool').then((data: any) => {
                    initSelectPool(data)
                    console.log('=== 加载完成 selectPool json')
                })
            )

            wait.push(
                JsonManager.Ins.getValue('entity').then((data: any) => {
                    initEntity(data)
                    console.log('=== 加载完成 entity json')
                })
            )
            wait.push(
                JsonManager.Ins.getValue('actor').then((data: any) => {
                    initActor(data)
                    console.log('=== 加载完成 actor json')
                })
            )
            wait.push(
                JsonManager.Ins.getValue('attribute').then((data: any) => {
                    initAttribute(data)
                    console.log('=== 加载完成 attribute json')
                })
            )
            wait.push(
                JsonManager.Ins.getValue('skill').then((data: any) => {
                    initSkill(data)
                    console.log('=== 加载完成 skill json')
                })
            )
            wait.push(
                JsonManager.Ins.getValue('talent').then((data: any) => {
                    initTalent(data)
                    console.log('=== 加载完成 talent json')
                })
            )


            let index = 1
            const func = (i: number) => {
                wait.push(
                    JsonManager.Ins.getValue('chapter' + i).then((data: any) => {
                        initChapter(data, i)
                        console.log(`=== 加载完成 chapter${i} json`)
                    })
                )
                JsonManager.Ins.getValue('chapter' + ++index).then(() => {
                    func(index)
                })
            }
            func(index)

            wait.push(
                JsonManager.Ins.getValue('levelPart').then((data: any) => {
                    initLevelPart(data)
                    console.log('=== 加载完成 levelPart json')
                })
            )
        })
    }
    loadResByEntityType(wait: Promise<unknown>[]) {
        for (const key in EntityTypeEnum) {
            if (//过滤出数字
                isNaN(Number(key))
            ) {
                continue
            }
            wait.push(this.loadRes(Number(key) as any))
        }
    }

    loadPrefab(wait: Promise<unknown>[]) {
        wait.push(
            ResourcesManager.Ins.loadDir('prefab', Prefab).then((prefabs) => {
                let ps = prefabs as Prefab[]
                for (const p of ps) {
                    let name = p.name as any
                    if (EntityTypeEnum[name]) {
                        ResourcesManager.Ins.prefabMap.set(EntityTypeEnum[name] as any, p)
                    }
                }
                console.log('=== 加载完成 prefab')
            })
        )
    }
    loadMaterial(wait: Promise<unknown>[]) {
        wait.push(
            ResourcesManager.Ins.loadDir('material', Material).then((materials) => {
                let ms = materials as Material[]
                for (const m of ms) {
                    let name = m.name as any
                    ResourcesManager.Ins.materialMap.set(name, m)
                }
                console.log('=== 加载完成 prefab')
            })
        )
    }

    async loadRes(type: EntityTypeEnum) {

        const sfArr: Array<SpriteFrame> = []
        const spriteFrame = await ResourcesManager.Ins.loadDir('entity/' + EntityTypeEnum[type], SpriteFrame) as SpriteFrame[]
        if (!spriteFrame.length) {
            /** 一般是prefab对象没有帧动画资源 */
            console.log(`=== 没有帧动画资源 ${EntityTypeEnum[type]}`)
            return
        }
        spriteFrame.map(v => {
            v.texture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR)
            sfArr.push(v)
        })

        sfArr.sort((a, b) => Number(a.name.match(/[0-9]/g)?.join("")) - Number(b.name.match(/[0-9]/g)?.join("")))
        ResourcesManager.Ins.textureMap.set(type, sfArr)
        console.log(`=== 加载完成 ${EntityTypeEnum[type]}`)

    }

    update(dt: number) {
        this.curTime += dt
        for (let i = 0; i < 4; i++) {
            this['run' + i].active = false
        }
        const index = Math.floor(this.curTime * 10 % 4)
        this['run' + index].active = true
    }

}